package com.oliet.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.oliet.entity.Users;
import com.oliet.exception.CustomException;
import com.oliet.exception.ErrorEnum;
import com.oliet.security.AccountUser;
import com.oliet.service.UsersService;
import com.oliet.util.IpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @author jiaZhenpeng
 * @Title: UserDetailServiceImpl
 * @Package com.oliet.service.impl
 * @Description:
 * @date 2023-11-29 17:36
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    UsersService usersService;

    @Override
    public UserDetails loadUserByUsername(String username) {
        if (username == null || "".equals(username)) {
            throw new RuntimeException("用户不能为空");
        }
        Users sysUser = this.usersService.getByUsername(username);
        if (sysUser == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }

        // 获取当前请求的IP地址
        String currentIp = IpUtil.getRequestIp();
        System.out.println("当前请求的IP地址：" + currentIp);
        //获取账号可用ip
        String availableIp = sysUser.getAvailableIp();
        if (StrUtil.isBlank(availableIp)) {
            //为空不处理
        } else {
            //使用,拆分availableIp
            String[] split = availableIp.split(",");
            List<String> list = CollectionUtil.toList(split);
            if (!list.contains(currentIp)) {
                throw new CustomException(ErrorEnum.NOT_HAVE_PERMISSION_TO_LOGIN);
            }
        }

        return new AccountUser(sysUser, getUserAuthority(sysUser.getId()));

    }

    /**
     * 获取用户权限信息（角色、菜单权限）
     *
     * @param userId
     * @return
     */
    public List<GrantedAuthority> getUserAuthority(Long userId) {
        // 实际怎么写以数据表结构为准，这里只是写个例子
        // 角色(比如ROLE_admin)，菜单操作权限(比如sys:user:list)
        String authority = this.usersService.getUserAuthorityInfo(userId);     // 比如ROLE_admin,ROLE_normal,sys:user:list,...

        return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
    }

}
